<template>
  <div style="display: flex;">
    <el-form :model="form" inline>
      <el-form-item label="店铺名:">
        <el-input v-model="form.taobaoUserNick" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">搜索</el-button>
      </el-form-item>
    </el-form>
    <el-button type="primary" @click="getAuthorization">获取授权信息</el-button>
    <el-input v-model="tokenTB" clearable style="width: 300px;height: 30px;" />
    <el-button type="primary" @click="setAuthor">保存授权信息</el-button>

  </div>
  <div class="table">
    <el-table ref="multipleTableRef" :data="tableData" style="width: 100%" @selection-change="handleSelectionChange"
      border>
      <el-table-column type="selection" width="55" />
      <el-table-column label="店铺名称" width="180">
        <template #default="scope">{{ scope.row.taobaoUserNick }}</template>
      </el-table-column>
      <el-table-column label="授权时间" width="180">
        <template #default="scope">{{ scope.row.updateTime }}</template>
      </el-table-column>
      <el-table-column label="到期时间" width="180">
        <template #default="scope">{{ scope.row.expireTime }}</template>
      </el-table-column>
      <el-table-column label="是否到期" width="180">
        <template #default="scope">{{ scope.row.isExpire == 0 ? '否' : '是' }}</template>
      </el-table-column>
      <el-table-column label="关联快递" width="180">
        <template #default="scope">
          <span class="headclass" @click="SetOrLook(scope.row)">点击查看/编辑</span>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button link type="primary" size="small" @click.prevent="delectShop(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <div class="page">
    <el-pagination v-model:current-page="currentPage4" v-model:page-size="pageSize4" :page-sizes="[10, 50, 100]"
      layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
      @current-change="handleCurrentChange" />
  </div>
  <!-- 编辑 -->
  <div>
    <el-dialog v-model="SetdialogVisible" width="530">
      <span>
        <div>

          店铺名称：<span>{{ shopName }}</span> <span style="margin-left: 50px;" class="headclass"
            @click.prevent="NewSetExpressDelivery">新增快递</span>
        </div>
        <div>
          <el-checkbox-group v-model="expressIds">
            <el-checkbox v-for="item in store.NewshopExpresslistSelectArr" :key="item.id" :label="item.id"
              :value="item.id">
              <div style="display: flex;">
                {{ item.name }}
                <div class="information_span" style="width: 300px;" :title="item.addressInfo">出单地址：{{
      item.addressInfo
    }}</div>
                <span style="margin-left: 20px;">
                  <el-button link type="primary" size="small" @click.prevent="setExpressDelivery(item)">
                    编辑
                  </el-button>
                  <el-button link type="primary" size="small" @click.prevent="delectshopExpress(item)">
                    删除
                  </el-button>
                </span>
              </div>
            </el-checkbox>
          </el-checkbox-group>
          <!-- <p v-for="item in store.NewshopExpresslistSelectArr" :key="item.id">
            <el-checkbox v-model="expressIds" @change="changeKuaidi(item)"></el-checkbox>

          </p> -->
        </div>
      </span>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="SetdialogVisible = false">取消</el-button>
          <el-button type="primary" @click="SetExpressdialogVisible">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
  <div>
    <el-dialog v-model="setExpressDeliveryDialogVisible" width="500">
      <span>
        <el-form :model="setWareHouseform" label-width="auto" style="max-width: 600px">
          <el-form-item label="快递名称：">
            <el-select v-model="setWareHouseform.code" style="width: 80px;" clearable value-key="id">
              <el-option :label="item.name" :value="item.code" v-for="item in store.shopExpressgetTbExpressListTable"
                :key="item.id" @click="getNames(item.name)" />
            </el-select>
          </el-form-item>
          <el-form-item label="发货人姓名：">
            <el-input v-model="setWareHouseform.sendPersonName" clearable />
          </el-form-item>
          <el-form-item label="发货人电话：">
            <el-input v-model="setWareHouseform.sendPersonPhone" clearable />
          </el-form-item>
          <el-form-item label="仓库收货省市区：" style="display: flex">
            <el-select v-model="receiveProvinceId" placeholder="省" style="width: 80px;" clearable value-key="id"
              @change="sysPcaDataListSelect(receiveProvinceId, '市', item)">
              <el-option :label="item.name" :value="item" v-for="item in province" :key="item.id" />
            </el-select>
            <el-select v-model="receiveCityId" placeholder="市" style="width: 80px;" clearable value-key="id"
              @change="sysPcaDataListSelect(receiveCityId, '区')">
              <el-option :label="item.name" :value="item" v-for="item in citys" :key="item.id" />
            </el-select>
            <el-select v-model="receiveAreaId" placeholder="区" style="width: 80px;" clearable value-key="id">
              <el-option :label="item.name" :value="item" v-for="item in districts" :key="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="发货详细地址：">
            <el-input v-model="setWareHouseform.sendDetailAddress" />
          </el-form-item>
          <el-form-item>
            <div style="display: flex;justify-content: space-between;width: 70%;margin:0 auto">
              <el-button type="primary" @click="onSubmitCompile">保存</el-button>
              <el-button @click="setExpressDeliveryDialogVisible=false">取消</el-button>
            </div>
          </el-form-item>
        </el-form>
      </span>
    </el-dialog>
  </div>
</template>

<script setup>

import { ref, onBeforeMount } from 'vue'
import { expressShopList, shopDelete, shopAuthorize, shopExpressDelete, shopExpressupdate, updateIsCheck, shopExpresscreate, sysPcaDataList, shopExpressdetail } from '@/api/index'
import { ElMessage } from 'element-plus'
import { useAlertsStore } from '@/store/index'
const store = useAlertsStore()
// do not use same name with ref
const form = ref({
  taobaoUserNick: '',
  pageSize: 10,
  pageNum: 1
})
const tokenTB = ref('')
const tableData = ref([])
onBeforeMount(() => {
  store.shopExpressgetTbExpressListbtn()
  getList()
})
const onSubmit = () => {
  console.log('submit!')
  getList()
}
const getList = () => {
  expressShopList(form.value).then(res => {
    const { data: { data } } = res
    total.value = data.total
    tableData.value = data.list
  })
}
// 分页
const currentPage4 = ref(1)
const pageSize4 = ref(10)
const total = ref(0)
const handleSizeChange = (val) => {
  console.log(`${val} items per page`)
  form.value.pageSize = val
  getList()
}
const handleCurrentChange = (val) => {
  console.log(`current page: ${val}`)
  form.value.pageNum = val
  getList()
}

// table
const multipleSelection = ref([])
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}
// 删除
const delectShop = (val) => {
  shopDelete({ id: val.id }).then(res => {
    getList()
    ElMessage.success('操作成功')
  })
}
// 编辑
const shopName = ref('')
const shopNameId = ref('')
const SetdialogVisible = ref(false)
const SetOrLook = (row) => {
  shopName.value = row.taobaoUserNick
  shopNameId.value = row.id
  expressIds.value = []
  store.shopExpresslistSelect(row.id)
    .then(() => {
      console.log('111')
      store.NewshopExpresslistSelectArr.forEach(element => {
        if (element.isUse === 1) {
          console.log('1111')
          expressIds.value.push(element.id)
        }
      })
      SetdialogVisible.value = true
    })
    .catch(error => {
      console.error('An error occurred:', error)
      // Handle errors here if needed
    })
}
// 删快递
const delectshopExpress = (val) => {
  shopExpressDelete({ id: val.id }).then(res => {
    ElMessage.success('操作成功')
    store.shopExpresslistSelect(shopNameId.value)
  })
}
// 添加
const SetExpressdialogVisible = () => {
  updateIsCheck({ id: shopNameId.value, ids: expressIds.value }).then(res => {
    ElMessage.success('操作成功')
    SetdialogVisible.value = false
  })
}
const expressIds = ref([])

// 修改详情
const setWareHouseform = ref({
  isUse: null,
  shopId: ''
})
const setExpressDeliveryDialogVisible = ref(false)
const setExpressDelivery = (rou) => {
  newOrSet.value = '2'
  shopExpressdetail({ id: rou.id }).then(res => {
    const { data: { data } } = res
    console.log('data')
    console.log(data)
    setWareHouseform.value = data
    setWareHouseform.value.isUse = rou.isUse
    sysPcaDataListSelect({ id: 0 }, '省')
      .then(() => sysPcaDataListSelect({ id: data.sendProvinceId }, '市'))
      .then(() => sysPcaDataListSelect({ id: data.sendCityId }, '区'))
      .then(() => {
        province.value.forEach(e => {
          console.log('e')
          if (e.id === data.sendProvinceId) {
            console.log(e)
            receiveProvinceId.value = e
          }
        })
        citys.value.forEach(e => {
          console.log('e')
          if (e.id === data.sendCityId) {
            console.log(e)
            receiveCityId.value = e
          }
        })
        districts.value.forEach(e => {
          if (e.id === data.sendAreaId) {
            console.log(e)
            receiveAreaId.value = e
          }
        })
        setExpressDeliveryDialogVisible.value = true
      })
      .catch(error => {
        console.error('An error occurred:', error)
      })
  })
}
// 省市
const receiveProvinceId = ref('')
const receiveCityId = ref('')
const receiveAreaId = ref('')
const province = ref([])
const citys = ref([])
const districts = ref([])

const sysPcaDataListSelect = async (val, name, item) => {
  console.log(val)
  const res = await sysPcaDataList(val.id)
  console.log(res)
  const { data: { data } } = res
  if (name === '省') {
    province.value = data
  } else if (name === '市') {
    citys.value = data
  } else if (name === '区') {
    districts.value = data
  }
}
const namess = ref('')
const getNames = (row) => {
  namess.value = row
  setWareHouseform.value.name = row
}
const onSubmitCompile = () => {
  if (newOrSet.value === '1') {
    shopExpresscreate({
      id: setWareHouseform.value.id,
      shopId: setWareHouseform.value.shopId,
      code: setWareHouseform.value.code,
      name: namess.value,
      sendPersonName: setWareHouseform.value.sendPersonName,
      sendPersonPhone: setWareHouseform.value.sendPersonPhone,
      sendProvinceId: receiveProvinceId.value.id,
      sendProvinceName: receiveProvinceId.value.name,
      sendCityId: receiveCityId.value.id,
      sendCityName: receiveCityId.value.name,
      sendAreaId: receiveAreaId.value.id,
      sendAreaName: receiveAreaId.value.name,
      sendDetailAddress: setWareHouseform.value.sendDetailAddress,
      isUse: ''
    }).then(res => {
      ElMessage.success('操作成功')
      setExpressDeliveryDialogVisible.value = false
      store.shopExpresslistSelect(shopNameId.value)
    })
  } else if (newOrSet.value === '2') {
    shopExpressupdate({
      id: setWareHouseform.value.id,
      shopId: setWareHouseform.value.shopId,
      name: setWareHouseform.value.name,
      code: setWareHouseform.value.code,
      sendPersonName: setWareHouseform.value.sendPersonName,
      sendPersonPhone: setWareHouseform.value.sendPersonPhone,
      sendProvinceId: receiveProvinceId.value.id,
      sendProvinceName: receiveProvinceId.value.name,
      sendCityId: receiveCityId.value.id,
      sendCityName: receiveCityId.value.name,
      sendAreaId: receiveAreaId.value.id,
      sendAreaName: receiveAreaId.value.name,
      sendDetailAddress: setWareHouseform.value.sendDetailAddress,
      isUse: setWareHouseform.value.isUse
    }).then(res => {
      ElMessage.success('操作成功')
      setExpressDeliveryDialogVisible.value = false
      store.shopExpresslistSelect(shopNameId.value)
    })
  }
}
// 新增快递
const newOrSet = ref('')
const NewSetExpressDelivery = () => {
  newOrSet.value = '1'
  setExpressDeliveryDialogVisible.value = true
  setWareHouseform.value = { isUse: null }
  setWareHouseform.value.shopId = shopNameId.value
  sysPcaDataListSelect({ id: 0 }, '省')
  receiveProvinceId.value = ''
  receiveCityId.value = ''
  receiveAreaId.value = ''
}
const getAuthorization = () => {
  const tempwindow = window.open('_blank')
  tempwindow.location.href = 'https://oauth.taobao.com/authorize?response_type=token&client_id=12253481&state=1212&view=web'
}
const setAuthor = () => {
  shopAuthorize({
    refreshToken: tokenTB.value,
    expressTypeId: 1
  }).then(res => {
    ElMessage.success('操作成功')
  })
}
</script>

<style lang='less' scoped></style>
